package model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import databean.FundBean;

public class SearchDAO {
	private List<Connection> connectionPool = new ArrayList<Connection>();

	private String jdbcDriver="com.mysql.jdbc.Driver";
	private String jdbcURL="jdbc:mysql:///webapp";
	private String tableName="fund";

	

	private synchronized Connection getConnection() {
		if (connectionPool.size() > 0) {
			return connectionPool.remove(connectionPool.size() - 1);
		}

		try {
			Class.forName(jdbcDriver);
		} catch (ClassNotFoundException e) {
			throw new AssertionError(e);
		}

		try {
			return DriverManager.getConnection(jdbcURL);
		} catch (SQLException e) {
			throw new AssertionError(e);
		}
	}

	private synchronized void releaseConnection(Connection con) {
		connectionPool.add(con);
	}

	
	public synchronized List<FundBean> search(String query) {
		try {
			Connection con = getConnection();

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select * from " + tableName
					+ " where name like '%" + query + "%'");

			List<FundBean> list = new ArrayList<FundBean>();
			while (rs.next()) {
				FundBean tmp = new FundBean(rs.getLong("fundID"));
				tmp.setName(rs.getString("name"));
				tmp.setSymbol(rs.getString("symbol"));
				list.add(tmp);
			}
			rs.close();
			stmt.close();
			releaseConnection(con);

			return list;

		} catch (SQLException e) {
			throw new AssertionError(e);
		}
	}

}
